import { defineStore } from "pinia";
import { login, register, getToken, isLogin,getUserInfo } from "@/api/user";
import { showLoadingToast, showFailToast, showNotify } from "vant";

export const useUserStore = defineStore({
  id: "app-user",
  state: () => ({
    userInfo: null,
    token: "",
    isLogin: false
  }),
  getters: {
    getUserInfo() {
      return this.userInfo;
    },
    getToken() {
      return this.token;
    },
    getIsLogined() {
      return this.isLogin;
    }
  },
  actions: {
    async login(data) {
      const loading = showLoadingToast({
        message: "登录中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      const res = await login(data);

      loading.close();
      if (!res.success) {
        showFailToast(res.message);
        return Promise.reject();
      }
      await this.getAsyncToken();
      showNotify({ type: "success", message: "登录成功！" });
    },
    async loginOut() {
      this.userInfo = null;
      this.token = "";
    },
    async register(data) {
      const loading = showLoadingToast({
        message: "注册中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      const res = await register(data);
      loading.close();
      if (!res.success) {
        showFailToast(res.message);
        return Promise.reject();
      }
      await this.getAsyncToken();
      showNotify({ type: "success", message: "注册成功！" });
    },
    async checkUserIsLogined() {
      const { result } = await isLogin();
      if (result) {
        await this.getAsyncToken();
      }
      this.isLogin = result;
      return result;
    },
    async getAsyncToken() {
      const { result } = await getToken();
      const { result: userInfo} = await getUserInfo()
      this.userInfo = userInfo;
      this.token = result;
    },
  },
});
